package com.example.wuyeguanli.activity;

import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.example.wuyeguanli.R;
import com.example.wuyeguanli.tools.ApiClient;
import com.example.wuyeguanli.tools.EspressoIdlingResource;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static org.junit.Assert.assertEquals;

@RunWith(AndroidJUnit4.class)
public class ComplaintSuggestionActivityTest {

    private static MockWebServer mockWebServer;
    private static String originalBaseUrl;

    @BeforeClass
    public static void setUpClass() throws IOException {
        originalBaseUrl = ApiClient.BASE_URL;
        mockWebServer = new MockWebServer();
        mockWebServer.start(8080);
        ApiClient.setBaseUrlForTesting(mockWebServer.url("/").toString());
    }

    @AfterClass
    public static void tearDownClass() throws IOException {
        if (mockWebServer != null) {
            mockWebServer.shutdown();
        }
        ApiClient.setBaseUrlForTesting(originalBaseUrl);
    }

    @Before
    public void setUp() {
        IdlingRegistry.getInstance().register(EspressoIdlingResource.getIdlingResource());
    }

    @After
    public void tearDown() {
        IdlingRegistry.getInstance().unregister(EspressoIdlingResource.getIdlingResource());
    }

    @Test
    public void testSubmitComplaint_NoImage_Success() throws InterruptedException {
        // 1. 准备Mock响应队列
        // 1.1 获取工单号
        mockWebServer.enqueue(new MockResponse().setBody("{\"state\":\"success\",\"error\":\"\",\"data\":\"C-TEST-123\"}"));
        // 1.2 提交投诉
        mockWebServer.enqueue(new MockResponse().setBody("{\"state\":\"success\",\"error\":\"\",\"data\":null}"));

        ActivityScenario<ComplaintSuggestionActivity> scenario = ActivityScenario.launch(ComplaintSuggestionActivity.class);

        // 2. 模拟用户操作
        onView(withId(R.id.telephone)).perform(replaceText("13700137001"));
        onView(withId(R.id.complaints_text)).perform(replaceText("楼道灯光太暗"), closeSoftKeyboard());
        onView(withId(R.id.btn_submit)).perform(click());

        // 3. 断言
        // 由于成功后页面会finish(), 我们可以验证MockServer接收到了正确的请求次数
        // Espresso 会自动等待IdlingResource空闲，所以到这里时，所有请求都已发完
        assertEquals(2, mockWebServer.getRequestCount()); // 验证发出了2个请求
    }

    @Test
    public void testSubmitComplaint_ValidationFail() {
        ActivityScenario.launch(ComplaintSuggestionActivity.class);

        // 不输入任何内容，直接点击提交
        onView(withId(R.id.btn_submit)).perform(click());

        // 验证提交按钮仍然可见，说明因为校验失败，没有发起网络请求
        onView(withId(R.id.btn_submit)).check(matches(isDisplayed()));
        // 并且MockServer没有收到任何请求
        assertEquals(0, mockWebServer.getRequestCount());
    }

    // 图片上传的测试比较复杂，因为它依赖于选择设备上的真实文件。
    // 在CI/CD环境中，通常会用更高级的技巧（如自定义Intent返回一个固定的Uri）来模拟。
    // 这里我们省略了带图片提交的测试，因为它在逻辑上与Repair模块的测试是重复的。
}